<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>光影聆动-多功能媒体播放器</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36CFC9',
            dark: '#1D2129',
            light: '#F2F3F5',
          },
          fontFamily: {
            inter: ['Inter', 'sans-serif'],
          },
        },
      }
    }
  </script>
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .player-shadow {
        box-shadow: 0 10px 30px rgba(22, 93, 255, 0.15);
      }
      .slider-thumb::-webkit-slider-thumb {
        @apply appearance-none w-4 h-4 rounded-full bg-primary cursor-pointer;
      }
      .slider-thumb::-moz-range-thumb {
        @apply w-4 h-4 rounded-full bg-primary cursor-pointer border-none;
      }
      .scrollbar-hide::-webkit-scrollbar {
        display: none;
      }
      .scrollbar-hide {
        -ms-overflow-style: none;
        scrollbar-width: none;
      }
    }
  </style>
</head>

<body class="bg-gray-100 font-inter min-h-screen flex flex-col">
  <!-- 顶部导航栏 -->
  <header class="bg-white shadow-sm sticky top-0 z-50">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
      <div class="flex items-center space-x-2">
        <i class="fa fa-play-circle text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-dark">光影聆动</h1>
      </div>版权所有：高浩然（计算机225班） 陈以利（计算机226班）
      <div class="hidden md:flex items-center space-x-4">
        <button class="text-gray-600 hover:text-primary transition-colors">
          <i class="fa fa-question-circle"></i>
          <span class="ml-1">帮助</span>
        </button>
        <button class="text-gray-600 hover:text-primary transition-colors">
          <i class="fa fa-cog"></i>
          <span class="ml-1">设置</span>
        </button>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-grow container mx-auto px-4 py-8">
    <div class="max-w-5xl mx-auto">
      <!-- 文件选择区域 -->
      <div class="bg-white rounded-xl p-6 mb-8 player-shadow transform transition-all duration-300 hover:shadow-lg">
        <div class="flex flex-col md:flex-row items-center justify-between gap-4">
          <div>
            <h2 class="text-lg font-semibold text-dark mb-1">选择媒体文件</h2>
            <p class="text-gray-500 text-sm">支持 MP3、WAV、MP4、WebM 等格式</p>
          </div>
          <div class="flex items-center space-x-3">
            <label for="file-input"
              class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg flex items-center cursor-pointer transition-all duration-300 transform hover:scale-105">
              <i class="fa fa-folder-open mr-2"></i>
              <span>浏览文件</span>
            </label>
            <input type="file" id="file-input" accept="audio/*, video/*" class="hidden" multiple />
          </div>
        </div>
      </div>

      <!-- 媒体播放区域 -->
      <div id="player-container"
        class="bg-white rounded-xl overflow-hidden player-shadow mb-8 opacity-0 transition-opacity duration-500">
        <!-- 媒体元素 -->
        <div class="relative bg-dark aspect-video flex items-center justify-center">
          <div id="no-media-placeholder" class="text-center text-gray-400">
            <i class="fa fa-film text-6xl mb-3"></i>
            <p>请选择一个媒体文件开始播放</p>
          </div>
          <video id="media-element" class="w-full h-full object-contain hidden"></video>
          <audio id="audio-element" class="w-full hidden"></audio>
        </div>

        <!-- 播放控制栏 -->
        <div class="p-4 bg-white">
          <!-- 进度条 -->
          <div class="mb-3">
            <div class="flex items-center justify-between text-xs text-gray-500 mb-1">
              <span id="current-time">00:00</span>
              <span id="total-time">00:00</span>
            </div>
            <div class="relative h-1 bg-gray-200 rounded-full overflow-hidden cursor-pointer group"
              id="progress-container">
              <div id="progress-bar" class="absolute top-0 left-0 h-full bg-primary rounded-full" style="width: 0%">
              </div>
              <div id="progress-buffer" class="absolute top-0 left-0 h-full bg-primary/20 rounded-full"
                style="width: 0%"></div>
              <div id="progress-handle"
                class="absolute top-1/2 -translate-y-1/2 w-3 h-3 bg-white border-2 border-primary rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                style="left: 0%"></div>
            </div>
          </div>

          <!-- 控制按钮 -->
          <div class="flex items-center justify-between">
            <div class="flex items-center space-x-4">
              <button id="prev-btn"
                class="w-10 h-10 rounded-full bg-primary text-white flex items-center justify-center hover:bg-primary/90 transition-all duration-300 transform hover:scale-105">
                <i class="fa fa-step-backward"></i>
              </button>
              <button id="play-pause-btn"
                class="w-10 h-10 rounded-full bg-primary text-white flex items-center justify-center hover:bg-primary/90 transition-all duration-300 transform hover:scale-105">
                <i class="fa fa-play"></i>
              </button>
              <button id="next-btn"
                class="w-10 h-10 rounded-full bg-primary text-white flex items-center justify-center hover:bg-primary/90 transition-all duration-300 transform hover:scale-105">
                <i class="fa fa-step-forward"></i>
              </button>
              <button id="mute-btn" class="text-gray-600 hover:text-primary transition-colors">
                <i class="fa fa-volume-up"></i>
              </button>
              <div class="w-20 relative hidden md:block">
                <input type="range" id="volume-slider" min="0" max="1" step="0.05" value="1"
                  class="w-full h-1 bg-gray-200 rounded-lg appearance-none cursor-pointer slider-thumb">
              </div>
            </div>
            <div class="flex items-center space-x-4">
              <button id="loop-mode-btn" class="text-gray-600 hover:text-primary transition-colors">
                <i class="fa fa-repeat"></i>
              </button>
              <button id="playback-speed-btn" class="text-gray-600 hover:text-primary transition-colors text-sm">
                1.0x
              </button>
              <button id="fullscreen-btn" class="text-gray-600 hover:text-primary transition-colors">
                <i class="fa fa-expand"></i>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 播放列表 -->
      <div class="bg-white rounded-xl p-6 player-shadow mb-8">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-semibold text-dark">播放列表</h2>
          <button id="clear-playlist-btn" class="text-gray-500 hover:text-red-500 text-sm transition-colors">
            <i class="fa fa-trash mr-1"></i> 清除列表
          </button>
        </div>
        <div id="playlist" class="space-y-2 max-h-60 overflow-y-auto scrollbar-hide">
          <div class="text-center text-gray-400 py-8" id="empty-playlist">
            <i class="fa fa-list text-3xl mb-2"></i>
            <p>暂无播放列表</p>
          </div>
        </div>
      </div>

      <!-- 播放历史 -->
      <div class="bg-white rounded-xl p-6 player-shadow">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-semibold text-dark">播放历史</h2>
          <div class="flex items-center space-x-2">
            <button id="clear-history-btn" class="text-gray-500 hover:text-red-500 text-sm transition-colors">
              <i class="fa fa-trash mr-1"></i> 清除历史
            </button>
            <button id="delete-selected-btn" class="text-gray-500 hover:text-red-500 text-sm transition-colors hidden">
              <i class="fa fa-trash mr-1"></i> 删除选中
            </button>
          </div>
        </div>
        <div id="history-list" class="space-y-2 max-h-60 overflow-y-auto scrollbar-hide">
          <div class="text-center text-gray-400 py-8" id="empty-history">
            <i class="fa fa-history text-3xl mb-2"></i>
            <p>暂无播放历史</p>
          </div>
        </div>
      </div>
    </div>
  </main>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 py-4">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
      <p>© 2025 MediaPlay | 多功能媒体播放器</p>
    </div>
  </footer>

  <!-- 播放速度菜单 -->
  <div id="speed-menu" class="fixed hidden bg-white rounded-lg shadow-lg p-2 z-50">
    <ul class="space-y-1">
      <li><button class="speed-option w-full text-left px-3 py-1 hover:bg-gray-100 rounded"
          data-speed="0.5">0.5x</button></li>
      <li><button class="speed-option w-full text-left px-3 py-1 hover:bg-gray-100 rounded"
          data-speed="0.75">0.75x</button></li>
      <li><button class="speed-option w-full text-left px-3 py-1 hover:bg-gray-100 rounded"
          data-speed="1.0">1.0x</button></li>
      <li><button class="speed-option w-full text-left px-3 py-1 hover:bg-gray-100 rounded"
          data-speed="1.25">1.25x</button></li>
      <li><button class="speed-option w-full text-left px-3 py-1 hover:bg-gray-100 rounded"
          data-speed="1.5">1.5x</button></li>
      <li><button class="speed-option w-full text-left px-3 py-1 hover:bg-gray-100 rounded"
          data-speed="2.0">2.0x</button></li>
    </ul>
  </div>

  <script>
    // 获取DOM元素
    const fileInput = document.getElementById('file-input');
    const playerContainer = document.getElementById('player-container');
    const mediaElement = document.getElementById('media-element');
    const audioElement = document.getElementById('audio-element');
    const noMediaPlaceholder = document.getElementById('no-media-placeholder');
    const playPauseBtn = document.getElementById('play-pause-btn');
    const muteBtn = document.getElementById('mute-btn');
    const volumeSlider = document.getElementById('volume-slider');
    const progressBar = document.getElementById('progress-bar');
    const progressBuffer = document.getElementById('progress-buffer');
    const progressHandle = document.getElementById('progress-handle');
    const progressContainer = document.getElementById('progress-container');
    const currentTime = document.getElementById('current-time');
    const totalTime = document.getElementById('total-time');
    const fullscreenBtn = document.getElementById('fullscreen-btn');
    const playbackSpeedBtn = document.getElementById('playback-speed-btn');
    const speedMenu = document.getElementById('speed-menu');
    const historyList = document.getElementById('history-list');
    const emptyHistory = document.getElementById('empty-history');
    const clearHistoryBtn = document.getElementById('clear-history-btn');
    const deleteSelectedBtn = document.getElementById('delete-selected-btn');
    const prevBtn = document.getElementById('prev-btn');
    const nextBtn = document.getElementById('next-btn');
    const loopModeBtn = document.getElementById('loop-mode-btn');
    const playlist = document.getElementById('playlist');
    const emptyPlaylist = document.getElementById('empty-playlist');
    const clearPlaylistBtn = document.getElementById('clear-playlist-btn');

    // 媒体元素变量
    let currentMedia = null;
    let isAudio = false;
    let playlistItems = [];
    let currentIndex = 0;
    let loopMode = 'list'; // 'single', 'list', 'random'

    // 初始化
    init();

    function init() {
      // 加载历史记录
      loadHistory();

      // 绑定事件监听器
      fileInput.addEventListener('change', handleFileSelect);
      playPauseBtn.addEventListener('click', togglePlayPause);
      muteBtn.addEventListener('click', toggleMute);
      volumeSlider.addEventListener('input', adjustVolume);
      progressContainer.addEventListener('click', seek);
      playbackSpeedBtn.addEventListener('click', toggleSpeedMenu);
      document.addEventListener('click', closeSpeedMenu);
      document.querySelectorAll('.speed-option').forEach(option => {
        option.addEventListener('click', setPlaybackSpeed);
      });
      fullscreenBtn.addEventListener('click', toggleFullscreen);
      clearHistoryBtn.addEventListener('click', clearHistory);
      deleteSelectedBtn.addEventListener('click', deleteSelectedHistory);
      prevBtn.addEventListener('click', playPrev);
      nextBtn.addEventListener('click', playNext);
      loopModeBtn.addEventListener('click', toggleLoopMode);
      clearPlaylistBtn.addEventListener('click', clearPlaylist);

      // 监听媒体事件
      mediaElement.addEventListener('timeupdate', updateProgress);
      mediaElement.addEventListener('loadedmetadata', updateTotalTime);
      mediaElement.addEventListener('progress', updateBuffer);
      mediaElement.addEventListener('ended', mediaEnded);

      audioElement.addEventListener('timeupdate', updateProgress);
      audioElement.addEventListener('loadedmetadata', updateTotalTime);
      audioElement.addEventListener('progress', updateBuffer);
      audioElement.addEventListener('ended', mediaEnded);

      // 快捷键支持
      document.addEventListener('keydown', handleKeyPress);
    }

    // 处理文件选择
    function handleFileSelect(e) {
      const files = e.target.files;
      if (files.length === 0) return;

      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const fileType = file.type;
        const fileURL = URL.createObjectURL(file);

        // 添加到播放列表
        addToPlaylist(file.name, fileType, fileURL);

        if (i === 0) {
          // 停止当前正在播放的媒体
          if (currentMedia) {
            currentMedia.pause();
            currentMedia.currentTime = 0;
          }

          // 检查文件类型
          isAudio = fileType.startsWith('audio/');

          // 设置媒体源
          if (isAudio) {
            audioElement.src = fileURL;
            mediaElement.classList.add('hidden');
            audioElement.classList.remove('hidden');
            currentMedia = audioElement;
          } else {
            mediaElement.src = fileURL;
            audioElement.classList.add('hidden');
            mediaElement.classList.remove('hidden');
            currentMedia = mediaElement;
          }

          // 显示播放器
          playerContainer.classList.remove('opacity-0');
          noMediaPlaceholder.classList.add('hidden');

          // 播放媒体
          currentMedia.play().catch(error => {
            console.error('播放错误:', error);
            alert('无法播放该文件，请尝试其他格式。');
          });

          // 添加到历史记录
          addToHistory(file.name, fileType, fileURL);
        }
      }
    }

    // 播放/暂停切换
    function togglePlayPause() {
      if (!currentMedia) return;

      if (currentMedia.paused) {
        currentMedia.play();
        playPauseBtn.innerHTML = '<i class="fa fa-pause"></i>';
      } else {
        currentMedia.pause();
        playPauseBtn.innerHTML = '<i class="fa fa-play"></i>';
      }
    }

    // 静音切换
    function toggleMute() {
      if (!currentMedia) return;

      currentMedia.muted = !currentMedia.muted;
      if (currentMedia.muted) {
        muteBtn.innerHTML = '<i class="fa fa-volume-off"></i>';
        volumeSlider.value = 0;
      } else {
        muteBtn.innerHTML = '<i class="fa fa-volume-up"></i>';
        volumeSlider.value = currentMedia.volume;
      }
    }

    // 调整音量
    function adjustVolume() {
      if (!currentMedia) return;

      currentMedia.volume = volumeSlider.value;
      if (volumeSlider.value == 0) {
        currentMedia.muted = true;
        muteBtn.innerHTML = '<i class="fa fa-volume-off"></i>';
      } else {
        currentMedia.muted = false;
        muteBtn.innerHTML = '<i class="fa fa-volume-up"></i>';
      }
    }

    // 更新进度条
    function updateProgress() {
      if (!currentMedia) return;

      const percent = (currentMedia.currentTime / currentMedia.duration) * 100;
      progressBar.style.width = `${percent}%`;
      progressHandle.style.left = `${percent}%`;
      currentTime.textContent = formatTime(currentMedia.currentTime);
    }

    // 更新缓冲进度
    function updateBuffer() {
      if (!currentMedia || !currentMedia.buffered.length) return;

      const bufferedEnd = currentMedia.buffered.end(currentMedia.buffered.length - 1);
      const duration = currentMedia.duration;

      if (duration > 0) {
        const loadPercentage = (bufferedEnd / duration) * 100;
        progressBuffer.style.width = `${loadPercentage}%`;
      }
    }

    // 更新总时长
    function updateTotalTime() {
      if (!currentMedia) return;

      totalTime.textContent = formatTime(currentMedia.duration);
    }

    // 格式化时间
    function formatTime(seconds) {
      if (isNaN(seconds)) return '00:00';

      const minutes = Math.floor(seconds / 60);
      seconds = Math.floor(seconds % 60);

      return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }

    // 跳转到指定位置
    function seek(e) {
      if (!currentMedia) return;

      const rect = progressContainer.getBoundingClientRect();
      const pos = (e.clientX - rect.left) / rect.width;
      currentMedia.currentTime = pos * currentMedia.duration;
    }

    // 切换播放速度菜单
    function toggleSpeedMenu(e) {
      e.stopPropagation();

      const rect = playbackSpeedBtn.getBoundingClientRect();
      speedMenu.style.top = `${rect.bottom + 5}px`;
      speedMenu.style.left = `${rect.left}px`;
      speedMenu.classList.toggle('hidden');
    }

    // 关闭播放速度菜单
    function closeSpeedMenu(e) {
      if (!speedMenu.contains(e.target) && e.target !== playbackSpeedBtn) {
        speedMenu.classList.add('hidden');
      }
    }

    // 设置播放速度
    function setPlaybackSpeed(e) {
      const speed = parseFloat(e.target.dataset.speed);
      if (currentMedia) {
        currentMedia.playbackRate = speed;
        playbackSpeedBtn.textContent = `${speed}x`;
      }
      speedMenu.classList.add('hidden');
    }

    // 切换全屏
    function toggleFullscreen() {
      if (!currentMedia) return;

      const player = isAudio ? playerContainer : mediaElement;

      if (!document.fullscreenElement) {
        if (player.requestFullscreen) {
          player.requestFullscreen();
        } else if (player.webkitRequestFullscreen) { /* Safari */
          player.webkitRequestFullscreen();
        } else if (player.msRequestFullscreen) { /* IE11 */
          player.msRequestFullscreen();
        }
        fullscreenBtn.innerHTML = '<i class="fa fa-compress"></i>';
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.webkitExitFullscreen) { /* Safari */
          document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) { /* IE11 */
          document.msExitFullscreen();
        }
        fullscreenBtn.innerHTML = '<i class="fa fa-expand"></i>';
      }
    }

    // 媒体播放结束
    function mediaEnded() {
      playPauseBtn.innerHTML = '<i class="fa fa-play"></i>';

      switch (loopMode) {
        case 'single':
          currentMedia.currentTime = 0;
          currentMedia.play();
          break;
        case 'list':
          playNext();
          break;
        case 'random':
          const randomIndex = Math.floor(Math.random() * playlistItems.length);
          playFromPlaylist(randomIndex);
          break;
      }
    }

    // 添加到历史记录
    function addToHistory(name, type, url) {
      const history = getHistory();
      const isAudio = type.startsWith('audio/');

      // 检查是否已存在相同的文件
      const existingIndex = history.findIndex(item => item.url === url);
      if (existingIndex !== -1) {
        history.splice(existingIndex, 1); // 移除旧记录
      }

      // 添加新记录到开头
      history.unshift({
        name,
        type,
        url,
        timestamp: new Date().toISOString()
      });

      // 限制历史记录数量为10
      if (history.length > 10) {
        history.pop();
      }

      // 保存历史记录
      localStorage.setItem('mediaHistory', JSON.stringify(history));

      // 更新历史记录UI
      renderHistory();
    }

    // 加载历史记录
    function loadHistory() {
      renderHistory();
    }

    // 渲染历史记录
    function renderHistory() {
      const history = getHistory();

      if (history.length === 0) {
        emptyHistory.classList.remove('hidden');
        deleteSelectedBtn.classList.add('hidden');
        return;
      }

      emptyHistory.classList.add('hidden');
      historyList.innerHTML = '';

      history.forEach(item => {
        const isAudio = item.type.startsWith('audio/');
        const historyItem = document.createElement('div');
        historyItem.className = 'flex items-center justify-between p-3 border-b border-gray-100 hover:bg-gray-50 transition-colors';
        historyItem.innerHTML = `
          <div class="flex items-center space-x-3">
            <input type="checkbox" class="history-checkbox">
            <div class="w-10 h-10 rounded bg-primary/10 flex items-center justify-center text-primary">
              <i class="fa ${isAudio ? 'fa-music' : 'fa-film'}"></i>
            </div>
            <div class="truncate">
              <p class="text-gray-800 font-medium truncate">${item.name}</p>
              <p class="text-xs text-gray-500">${isAudio ? '音频' : '视频'} • ${formatDate(item.timestamp)}</p>
            </div>
          </div>
          <div class="flex items-center space-x-3">
            <button class="play-history text-primary hover:text-primary/80 transition-colors" data-url="${item.url}" data-type="${item.type}">
              <i class="fa fa-play-circle"></i>
            </button>
            <button class="delete-history text-gray-500 hover:text-red-500 transition-colors" data-url="${item.url}">
              <i class="fa fa-trash"></i>
            </button>
          </div>
        `;

        historyList.appendChild(historyItem);

        // 绑定播放历史记录事件
        const playBtn = historyItem.querySelector('.play-history');
        playBtn.addEventListener('click', () => {
          playFromHistory(item.url, item.type, item.name);
        });

        // 绑定单个删除事件
        const deleteBtn = historyItem.querySelector('.delete-history');
        deleteBtn.addEventListener('click', () => {
          deleteSingleHistory(item.url);
        });

        // 绑定多选框事件
        const checkbox = historyItem.querySelector('.history-checkbox');
        checkbox.addEventListener('change', checkSelected);
      });
    }

    // 从历史记录中播放
    function playFromHistory(url, type, name) {
      // 停止当前播放的媒体
      if (currentMedia) {
        currentMedia.pause();
        currentMedia.currentTime = 0;
      }

      // 等待0.5秒后播放新的媒体
      setTimeout(() => {
        isAudio = type.startsWith('audio/');

        if (isAudio) {
          audioElement.src = url;
          mediaElement.classList.add('hidden');
          audioElement.classList.remove('hidden');
          currentMedia = audioElement;
        } else {
          mediaElement.src = url;
          audioElement.classList.add('hidden');
          mediaElement.classList.remove('hidden');
          currentMedia = mediaElement;
        }

        // 显示播放器
        playerContainer.classList.remove('opacity-0');
        noMediaPlaceholder.classList.add('hidden');

        // 播放媒体
        currentMedia.play().catch(error => {
          console.error('播放错误:', error);
          alert('无法播放该文件，请尝试其他格式。');
        });
      }, 500);
    }

    // 获取历史记录
    function getHistory() {
      return JSON.parse(localStorage.getItem('mediaHistory')) || [];
    }

    // 清除历史记录
    function clearHistory() {
      localStorage.removeItem('mediaHistory');
      renderHistory();
    }

    // 删除单个历史记录
    function deleteSingleHistory(url) {
      const history = getHistory();
      const newHistory = history.filter(item => item.url !== url);
      localStorage.setItem('mediaHistory', JSON.stringify(newHistory));
      renderHistory();
    }

    // 删除选中的历史记录
    function deleteSelectedHistory() {
      const checkboxes = document.querySelectorAll('.history-checkbox:checked');
      const history = getHistory();
      const urlsToDelete = Array.from(checkboxes).map(checkbox => {
        const parent = checkbox.closest('.flex');
        const playBtn = parent.nextElementSibling.querySelector('.play-history');
        return playBtn.dataset.url;
      });

      const newHistory = history.filter(item => !urlsToDelete.includes(item.url));
      localStorage.setItem('mediaHistory', JSON.stringify(newHistory));
      renderHistory();
    }

    // 检查是否有选中的历史记录
    function checkSelected() {
      const checkboxes = document.querySelectorAll('.history-checkbox:checked');
      if (checkboxes.length > 0) {
        deleteSelectedBtn.classList.remove('hidden');
      } else {
        deleteSelectedBtn.classList.add('hidden');
      }
    }

    // 格式化日期
    function formatDate(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }

    // 添加到播放列表
    function addToPlaylist(name, type, url) {
      const isAudio = type.startsWith('audio/');
      const newItem = { name, type, url };
      playlistItems.push(newItem);

      const playlistItem = document.createElement('div');
      playlistItem.className = 'flex items-center justify-between p-3 border-b border-gray-100 hover:bg-gray-50 transition-colors';
      playlistItem.innerHTML = `
        <div class="flex items-center space-x-3">
          <div class="w-10 h-10 rounded bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa ${isAudio ? 'fa-music' : 'fa-film'}"></i>
          </div>
          <div class="truncate">
            <p class="text-gray-800 font-medium truncate">${name}</p>
            <p class="text-xs text-gray-500">${isAudio ? '音频' : '视频'}</p>
          </div>
        </div>
        <div class="flex items-center space-x-3">
          <button class="play-playlist text-primary hover:text-primary/80 transition-colors" data-index="${playlistItems.length - 1}">
            <i class="fa fa-play-circle"></i>
          </button>
          <button class="delete-playlist text-gray-500 hover:text-red-500 transition-colors" data-index="${playlistItems.length - 1}">
            <i class="fa fa-trash"></i>
          </button>
        </div>
      `;

      playlist.appendChild(playlistItem);

      // 绑定播放列表项事件
      const playBtn = playlistItem.querySelector('.play-playlist');
      playBtn.addEventListener('click', () => {
        playFromPlaylist(parseInt(playBtn.dataset.index));
      });

      // 绑定删除列表项事件
      const deleteBtn = playlistItem.querySelector('.delete-playlist');
      deleteBtn.addEventListener('click', () => {
        deleteFromPlaylist(parseInt(deleteBtn.dataset.index));
      });

      emptyPlaylist.classList.add('hidden');
    }

    // 从播放列表中播放
    function playFromPlaylist(index) {
      currentIndex = index;
      const item = playlistItems[index];
      const type = item.type;
      const url = item.url;
      const name = item.name;

      // 停止当前播放的媒体
      if (currentMedia) {
        currentMedia.pause();
        currentMedia.currentTime = 0;
      }

      // 等待0.5秒后播放新的媒体
      setTimeout(() => {
        isAudio = type.startsWith('audio/');

        if (isAudio) {
          audioElement.src = url;
          mediaElement.classList.add('hidden');
          audioElement.classList.remove('hidden');
          currentMedia = audioElement;
        } else {
          mediaElement.src = url;
          audioElement.classList.add('hidden');
          mediaElement.classList.remove('hidden');
          currentMedia = mediaElement;
        }

        // 显示播放器
        playerContainer.classList.remove('opacity-0');
        noMediaPlaceholder.classList.add('hidden');

        // 播放媒体
        currentMedia.play().catch(error => {
          console.error('播放错误:', error);
          alert('无法播放该文件，请尝试其他格式。');
        });

        // 添加到历史记录
        addToHistory(name, type, url);
      }, 500);
    }

    // 删除播放列表项
    function deleteFromPlaylist(index) {
      playlistItems.splice(index, 1);
      renderPlaylist();
    }

    // 渲染播放列表
    function renderPlaylist() {
      if (playlistItems.length === 0) {
        emptyPlaylist.classList.remove('hidden');
        return;
      }

      emptyPlaylist.classList.add('hidden');
      playlist.innerHTML = '';

      playlistItems.forEach((item, index) => {
        const isAudio = item.type.startsWith('audio/');
        const playlistItem = document.createElement('div');
        playlistItem.className = 'flex items-center justify-between p-3 border-b border-gray-100 hover:bg-gray-50 transition-colors';
        playlistItem.innerHTML = `
          <div class="flex items-center space-x-3">
            <div class="w-10 h-10 rounded bg-primary/10 flex items-center justify-center text-primary">
              <i class="fa ${isAudio ? 'fa-music' : 'fa-film'}"></i>
            </div>
            <div class="truncate">
              <p class="text-gray-800 font-medium truncate">${item.name}</p>
              <p class="text-xs text-gray-500">${isAudio ? '音频' : '视频'}</p>
            </div>
          </div>
          <div class="flex items-center space-x-3">
            <button class="play-playlist text-primary hover:text-primary/80 transition-colors" data-index="${index}">
              <i class="fa fa-play-circle"></i>
            </button>
            <button class="delete-playlist text-gray-500 hover:text-red-500 transition-colors" data-index="${index}">
              <i class="fa fa-trash"></i>
            </button>
          </div>
        `;

        playlist.appendChild(playlistItem);

        // 绑定播放列表项事件
        const playBtn = playlistItem.querySelector('.play-playlist');
        playBtn.addEventListener('click', () => {
          playFromPlaylist(parseInt(playBtn.dataset.index));
        });

        // 绑定删除列表项事件
        const deleteBtn = playlistItem.querySelector('.delete-playlist');
        deleteBtn.addEventListener('click', () => {
          deleteFromPlaylist(parseInt(deleteBtn.dataset.index));
        });
      });
    }

    // 清除播放列表
    function clearPlaylist() {
      playlistItems = [];
      renderPlaylist();
    }

    // 播放上一首
    function playPrev() {
      if (playlistItems.length === 0) return;

      currentIndex = (currentIndex - 1 + playlistItems.length) % playlistItems.length;
      playFromPlaylist(currentIndex);
    }

    // 播放下一首
    function playNext() {
      if (playlistItems.length === 0) return;

      currentIndex = (currentIndex + 1) % playlistItems.length;
      playFromPlaylist(currentIndex);
    }

    // 切换循环模式
    function toggleLoopMode() {
      switch (loopMode) {
        case 'single':
          loopMode = 'list';
          loopModeBtn.innerHTML = '<i class="fa fa-repeat"></i>';
          break;
        case 'list':
          loopMode = 'random';
          loopModeBtn.innerHTML = '<i class="fa fa-random"></i>';
          break;
        case 'random':
          loopMode = 'single';
          // 使用 fa-refresh 替代不存在的 fa-repeat-one
          loopModeBtn.innerHTML = '<i class="fa fa-refresh"></i>';
          break;
      }
    }

    // 处理键盘快捷键
    function handleKeyPress(e) {
      switch (e.key) {
        case ' ':
          togglePlayPause();
          break;
        case 'ArrowLeft':
          playPrev();
          break;
        case 'ArrowRight':
          playNext();
          break;
        case 'm':
          toggleMute();
          break;
        case 'f':
          toggleFullscreen();
          break;
      }
    }
  </script>
</body>

</html>